3. Plotting with Matplotlib

Matplotlib is a standard plotting library of python. We begin by importing it first along with numpy.

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

The most widely used function in matplotlib is plot, which allows you to plot 1D and 2D data. Here is a simple example:

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7fc28768b2d0>]
../_images/intro2viz_4_1.png

We can easily customize the style of plots for poster/talk/paper

print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
plt.style.use(['seaborn-white'])
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7fc287515890>]
../_images/intro2viz_7_1.png

if we want to customize plots it is better to plot by first defining fig and ax objecs which have manuy methods for customizing figure resolution and plot related aspects respecticely.

fig, ax = plt.subplots()

y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
ax.plot(x, y_sin)
ax.plot(x, y_cos)

# Specify labels
ax.set_xlabel('x axis label')
ax.set_ylabel('y axis label')
ax.set_title('Sine and Cosine')
ax.legend(['Sine', 'Cosine'])

#fig.savefig("myfig.pdf")
<matplotlib.legend.Legend at 0x7fc28753cd50>
../_images/intro2viz_9_1.png

3.2. Pandas and seaborn! a power couple for multivariate statistics visualization

# Normal distribution of points 
n_points=200

df = pd.DataFrame({ 'X':    1*np.random.randn(n_points), 
                    'Y':    5*np.random.randn(n_points), 
                    'Z':    1+5*np.random.randn(n_points),
                    'time': np.linspace(0,n_points,n_points)
                  })
sns.jointplot(data=df, x='X', y='Z',
              kind="kde", cmap='RdBu_r')
<seaborn.axisgrid.JointGrid at 0x7fc275efe4d0>
../_images/intro2viz_29_1.png

3.3. Interactive plots

3.3.1. Using widgets

Suppose we would like to explore how the variation of parameter \(\lambda\) affects the following function of a standing wave:

\[ f(x) = sin \Big(\frac{2\pi x}{\lambda}\Big) \]

Step 1 Make a python-function which creates a plot as a function of a parameter(s) of interest.

Step 2 Add an interactive widget on top to vary the parameter.

from ipywidgets import widgets
@widgets.interact(L=(1,12))    # Vary between 0.2 and 20

def wave(L=1):          # We make default value equal to 1
    
    x=np.linspace(-10,10,1000)
        
    f = np.sin(2*np.pi*x/L)
        
    plt.plot(x,f, lw=2, color='blue')

3.4. More interactiviy via Plotly-express

  • Plotly is large multi-language interactive graphing library that covers Python/Julia/R.

  • Plotly-dash is a framework for building web dashborads with itneractive plotly graphs.

  • Plotly-express is a high level library for quick visualizations whihc is similiar to seaborn vs matploltib in its philosophy

Check out this cool website built using Dash-Plotly

import plotly.express as px
px.density_heatmap(df, x='X', y='Y')
#px.line(df, x='X', y='Y')
#px.scatter(df, x='X', y='Y')
#px.area(df, x='X', y='Y')
#px.histogram(df, x="X")
fig = px.scatter(df, x="X", y="Y", size=20*np.ones(n_points), 
                 animation_frame="time", animation_group='Y', color='Y',
                 range_x=[-20,20], range_y=[-20,20]
                 )
fig.show()

3.4.1. Too many libraries for visualization in pyviz universe? Enter Holoviews!

We all can agree there are just too many options for visualizing data and sometimes it is impossible to pick one and stick with becaue different libaries have different strengths when it comes visualizing different kinds of data. Plotly does a gread job with 3D visualization while matploltib is mostly desinged for 2D plots. Seaborn has everying one needs to genreate statistical plots while plotly may cover ony a subgroup of seaborn, etc. One emerging idea in scientific software desing is to create library agnostic tools. E.g if you want to plot histogram you can do it either using several different libraries or using a library agnsotic tool by specifiying the particular library interface for the visualization.

“Stop plotting your data - annotate your data and let it visualize itself”

# May have to run this in GoogleCollab to show the plots
#!pip install -q holoviews 
import holoviews as hv
hv.extension('plotly') # try 'bokeh' or 'matplotlib'

data = df[['X', 'Y']].values

#hv.Curve(data)
hv.Scatter(data) + hv.Curve(data) + hv.Points(data) + hv.Bivariate(data)
#hv.Histogram(df['X'], density=True, bins=50)
#Example of 3D plot
hv.extension('plotly') # try 'bokeh' or 'matplotlib'

Z = np.sin( np.random.randn(40,40) )**5

hv.Surface(Z, bounds=(-5, -5, 5, 5))
def wave(L=0, phi=0, a=1):          # We make default value equal to 1
    
    x=np.linspace(-10,10,1000)
        
    return hv.Curve((x, a*np.sin(2*np.pi*x/L+phi)))

hv.DynamicMap(wave, kdims=['a', 'L', 'phi']).redim.range(a=(0,2), L=(0.5,1), phi=(0,1))

3.5. Additional resoruces.

Matplotlib has a huge scientific user base. This means that you can always find a good working template of any kind of visualization which you want to make. With basic understanding of matplotlib and some solid googling skills you can go very far. Here are some additional resources that you may find helpful